<template>
  <div class="app-container">
    <el-form ref="form" :model="form" label-width="120px">
      <el-row>
      <el-col :span="8">
      <el-form-item label="科目" >
        <el-select v-model="form.region" placeholder="请选择科目">
          <el-option label="数学" value="1" />
          <el-option label="物理" value="2" />
        </el-select>
      </el-form-item>
    </el-col>
    <el-col :span="10">
      <el-form-item label="题型">
        <el-radio-group v-model="form.resource">
          <el-radio :label="1">单选题</el-radio>
          <el-radio :label="2">多选题</el-radio>
          <el-radio :label="3">填空题</el-radio>
          <el-radio :label="4">解答题</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-col>
    </el-row>
    <el-row>
       <el-form-item label="题目标签：">
        <el-input v-model="form.tag"></el-input>
      </el-form-item>
    </el-row>  
      <el-form-item label="题目内容：">
        <div id="demo1" >
        </div>
      </el-form-item>   
     <el-form-item > 
        <div class="right-align">
        <el-button @click="onCancel" >取消</el-button>
        <el-button type="primary" @click="onSubmit">提交</el-button> 
      </div>
     </el-form-item>  
    </el-form>
  </div>
</template>

<script>

import { mapGetters } from 'vuex'

// 引入 wangEditor
import WangEditor from 'wangeditor'
import createKityformula from './components/kityformula'
import myscriptMath from './components/myscript-math-web'
import { addQuestion, uploadFile } from '@/api/examApi.js'

import {Base64} from 'js-base64'

export default {
  data() {
    return {
      form: {
        region: '1',
        resource: 1,
        desc: '',
        tag: ''
      },
      editor: null,
      baseUrl: process.env.VUE_APP_BASE_API + '/math/uploadfiles.aspx',
      editorData: ''
    }
  },
  mounted () {
    this.createEditor()
  
  },
  methods: { 
    createEditor(){
        const editor = new WangEditor('#demo1')

    // 配置菜单栏，删减菜单，调整顺序
    // editor.config.menus = ['bold', 'head', 'link', 'italic', 'underline']

    // 配置行高
    // editor.config.lineHeights = ['1', '1.15', '1.6', '2', '2.5', '3']

    // 获取必要的变量，这些在下文中都会用到
    const { $ } = WangEditor
    const { PanelMenu, Panel } = WangEditor

    class Kityformula extends PanelMenu {
      // 公式输入插件
      constructor (editors) {
        const $elem = WangEditor.$(
          `<div class="w-e-menu">公式</div>`
        )
        super($elem, editors)
      }

      // 菜单点击事件
      clickHandler () {
        // 做任何你想做的事情
        // 可参考【常用 API】文档，来操作编辑器
        const conf = createKityformula(editor)
        const panel = new Panel(this, conf)
        panel.create()
      }

      tryChangeActive () {}
    }

    class Myscript extends PanelMenu {
      // 公式手写插件
      constructor (editors) {
        const $elem = WangEditor.$(
          `<div class="w-e-menu">手写</div>`
        )
        super($elem, editors)
      }

      // 菜单点击事件
      clickHandler () {
        // 做任何你想做的事情
        // 可参考【常用 API】文档，来操作编辑器
        const conf = myscriptMath(editor)
        const panel = new Panel(this, conf)
        panel.create()
      }

      tryChangeActive () {}
    }

    class MyDrawTool extends PanelMenu {
      // 自绘几何插件
      constructor (editors) {
        const $elem = WangEditor.$(
          `<div class="w-e-menu">画图</div>`
        )
        super($elem, editors)
      }
      // 菜单点击事件
      clickHandler () {
       
      }

      tryChangeActive () {}
    }

    // 注册菜单
    const kityformulaKey = 'kityformulaKey' // 菜单 key ，各个菜单不能重复
    editor.menus.extend('kityformulaKey', Kityformula)

    // 注册菜单
    const myscriptKey = 'myscriptKey' // 菜单 key ，各个菜单不能重复
    editor.menus.extend('myscriptKey', Myscript)

    const mydrawtoolKey = 'mydrawtoolKey' // 菜单 key ，各个菜单不能重复
    editor.menus.extend('mydrawtoolKey', MyDrawTool)

    // 将菜单加入到 editor.config.menus 中
    // 也可以通过配置 menus 调整菜单的顺序，参考【配置菜单】部分的文档
    editor.config.menus = editor.config.menus.concat(kityformulaKey)
    editor.config.menus = editor.config.menus.concat(myscriptKey)
    editor.config.menus = editor.config.menus.concat(mydrawtoolKey)

    editor.config.height = 350
    editor.config.weight = 30
    editor.config.uploadImgShowBase64 = false   //如果为true，则不用配置下面的
    editor.config.uploadImgMaxLength = 5 // 一次最多上传 5 个图片

    editor.config.showLinkImg  = false   //隐藏插入网络图片的功能
    editor.config.uploadImgServer = this.baseUrl
    editor.config.uploadImgHooks = {
      onSuccess : function(xhr, editor, result) { 
        console.log("上传成功"); 
      },
      fail : function(xhr, editor, result) {
         console.log("上传失败,原因是"+result);
      },
      error : function(xhr, editor) { 
        console.log("上传出错");
      },
      customInsert:function(insertImgFn,resutl){ 
        for(var j = 0;j < resutl.data.length;j++){
          //alert(JSON.stringify(resutl.data[j]))
          insertImgFn(resutl.data[j].url)
        }
      }
    }
    /*editor.config.customUploadImg = async function (resultFiles, insertImgFn){
      let data = resultFiles[0];
      if (data.size > 2 * 1024 * 1024) {
        that.$message.error("上传图片不能超过2MB!");
        return false;
      }
      
      const isJpgOrPng = /jpg|png|jpeg|gif|wmf|svg|tiff/.test(data.type);
      if (!isJpgOrPng) {
        that.$message.error("请上传图片!");
        return false;
      }
      var uploadData = new FormData();
      for (var i = 0; i < resultFiles.length; i++) {
        uploadData.append(resultFiles[i].name, resultFiles[i]);
        //uploadData.append('img[]',resultFiles[i])
      }
      console.log(uploadData)
      alert((uploadData))
      const p = new Promise((res)=>{
			res(uploadNewsPicMtd(uploadData,1))
      })
      p.then(res => {
        res.forEach(x=>{
          insertImgFn(x.url)
        })
      })
  
    }*/

    // 配置 onchange 回调函数，将数据同步到 vue 中
    editor.config.onchange = newHtml => {
      this.editorData = newHtml
      console.log(this.editorData)
    }
    // 创建编辑器
    editor.create()
    this.editor = editor
    },
    onSubmit() {
      let _this = this
      //this.$message('submit!')
      const myData = this.editor.txt.html();
      //var text = editor.$txt.text();
      //alert(myData)
      var myText = Base64.encode(myData);
      //alert(myText);
      //console.log(myText)
      //let formData = new FormData();
      //formData.append('subject', this.form.region);
      //formData.append('type', this.form.resource);
      //formData.append('content', myText);
      //formData.append('auth',"wenxinfly") 
      //console.log(JSON.stringify(formData))
      var jsData = { "subject":this.form.region, "type":this.form.resource, "content":myText, "tag":this.form.tag, "auth":_this.username }
      //alert(JSON.stringify(jsData))
      addQuestion(jsData).then(function (res){
        console.log(res)
        if (res.code == 200){
          _this.$message.success(res.message)
        }
      })  
    },
    resetForm () {
      //let lastId = this.form.id
      this.$refs['form'].resetFields()
      this.form = {
        //id: null,
        subjectId: '1',
      }
      this.editor.txt.html('')
      //this.form.id = lastId
    },
    onCancel() {
      this.$message({
        message: 'cancel!',
        type: 'warning'
      })
    },
    async uploadNewsPicMtd(img) {
     let res = await this.uploadFile(img)
     let imgUrl = []
     for(let i=0; i<res.data.length;i++){
         imgUrl.push({url:res.data[i].url})
     }
     return imgUrl
    }
  },
   computed: {
    ...mapGetters({username:"name", score:"score",rank:"rank" }),
  },
}
</script>

<style scoped>
@import url("http://at.alicdn.com/t/font_2161824_78bvz3356e.css");
.line{
  text-align: center;
}
.editorContent{
    height:550px;
    max-height:580px;
    border:1px solid #ccc;
}
.right-align {
  position: absolute;
  right: 0%;
}
</style>

